package com.wwdx.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

/**
 * 数据库JDBC公共类
 * @author liguoliang
 */
public class Jdbc {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private String url,user,password;

	{
        String path = "/properties/database.properties";
        ConfigReader configReader = new ConfigReader(path);
        url = configReader.get("db.url");
        user = configReader.get("db.user");
        password = AesUtil.decryptStrWithAes(configReader.get("db.password"), ConstantHolder.Constant.DBENCODE_RULES);
        try {
            //加载驱动
            Class.forName(configReader.get("db.driverClassName"));
        } catch (ClassNotFoundException e) {
            logger.error("错误信息：{}",e.getMessage());
        }
    }

	/**
	 * 获取连接
	 */
	public Connection getConnection() {
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
            logger.error("错误信息：{}",e.getMessage());
		}
		return connection;
	}

	/**
	 * 获取清单对象
	 */
	public Statement getStatement(Connection connection) {
		Statement statement = null;
		try {
			//判断连接是否为空 如果为空创建一个新的
			if (connection == null) {
				connection = this.getConnection();
			}
			statement = connection.createStatement();
		} catch (SQLException e) {
            logger.error("错误信息：{}",e.getMessage());
		}
		return statement;
	}

    /**
     * 获取预处理清单对象
     */
    public PreparedStatement getPstmt(Connection connection, String sql) {
        PreparedStatement preparedStatement = null;
        try {
            //判断连接是否为空 如果为空创建一个新的
            if (connection == null) {
                connection = this.getConnection();
            }
            preparedStatement = connection.prepareStatement(sql);
        } catch (SQLException e) {
            logger.error("错误信息：{}",e.getMessage());
        }
        return preparedStatement;
    }

    /**
     * 关闭连接
     */
    private void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.error("错误信息：{}",e.getMessage());
            }
        }
    }

    /**
	 * 关闭清单对象
	 */
	private void closeStatement(Statement statement) {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
                logger.error("错误信息：{}",e.getMessage());
			}
		}
	}

	/**
	 * 关闭结果集合
	 */
	private void closeResultSet(ResultSet resultSet) {
		if (resultSet != null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
                logger.error("错误信息：{}",e.getMessage());
			}
		}
	}

	/**
	 * 释放所有的资源
	 */
	public void closeConnStmtRs(Connection connection, Statement statement, ResultSet resultSet) {
		this.closeResultSet(resultSet);
		this.closeStatement(statement);
		this.closeConnection(connection);
	}
}